from dataclasses import dataclass, field
from datetime import datetime
from typing import Optional, List, Dict
import os

@dataclass
class FileInfo:
    """文件信息数据模型"""
    path: str
    name: str
    size: int
    extension: str
    category: str
    is_directory: bool
    created_time: datetime
    modified_time: datetime
    parent_path: str
    depth: int
    is_system_file: bool = False
    is_large_file: bool = False
    access_time: Optional[datetime] = None
    
    @property
    def size_display(self) -> str:
        """格式化显示文件大小"""
        return self.format_size(self.size)
    
    @staticmethod
    def format_size(size_bytes: int) -> str:
        """格式化文件大小"""
        if size_bytes == 0:
            return "0 B"
        
        size_names = ["B", "KB", "MB", "GB", "TB"]
        i = 0
        while size_bytes >= 1024 and i < len(size_names) - 1:
            size_bytes /= 1024.0
            i += 1
        return f"{size_bytes:.2f} {size_names[i]}"

@dataclass
class ScanStatistics:
    """扫描统计信息"""
    total_files: int = 0
    total_directories: int = 0
    total_size: int = 0
    scan_duration: float = 0.0
    start_time: Optional[datetime] = None
    end_time: Optional[datetime] = None
    error_count: int = 0
    scanned_paths: int = 0
    large_files: List['FileInfo'] = field(default_factory=list)
    
    # 兼容main.py所需的字段
    scan_time: Optional[str] = None
    size_categories: Dict[str, int] = field(default_factory=dict)
    type_categories: Dict[str, int] = field(default_factory=dict)
    large_file_count: int = 0
    
    # 别名，用于兼容
    @property
    def total_dirs(self) -> int:
        return self.total_directories
    
    @total_dirs.setter
    def total_dirs(self, value: int):
        self.total_directories = value
    
    @property
    def files_per_second(self) -> float:
        """计算每秒扫描文件数"""
        if self.scan_duration > 0:
            return self.total_files / self.scan_duration
        return 0.0
    
    def format_duration(self) -> str:
        """格式化扫描耗时"""
        hours, remainder = divmod(self.scan_duration, 3600)
        minutes, seconds = divmod(remainder, 60)
        if hours > 0:
            return f"{int(hours)}小时{int(minutes)}分钟{int(seconds)}秒"
        elif minutes > 0:
            return f"{int(minutes)}分钟{int(seconds)}秒"
        else:
            return f"{int(seconds)}秒"

@dataclass
class CategoryStats:
    """分类统计信息"""
    category_name: str
    file_count: int = 0
    total_size: int = 0
    avg_file_size: float = 0.0
    
    @property
    def size_display(self) -> str:
        return FileInfo.format_size(self.total_size)
    
    @property
    def avg_size_display(self) -> str:
        return FileInfo.format_size(int(self.avg_file_size))

@dataclass
class SoftwareInfo:
    """软件信息数据模型"""
    # 基础信息
    name: str                    # 软件名称
    version: str                 # 软件版本
    publisher: str              # 发布商
    description: str            # 软件描述
    
    # 安装信息
    install_path: str           # 安装路径
    executable_path: str        # 主执行文件路径
    install_date: Optional[datetime] = None  # 安装日期
    
    # 统计信息
    file_count: int = 0         # 包含文件数量
    total_size: int = 0         # 总大小（字节）
    
    # 分类信息
    category: str = "其他软件"   # 软件分类
    confidence: float = 0.0     # 识别置信度 (0.0-1.0)
    
    # 特征信息
    signature_files: List[str] = None  # 特征文件列表
    directory_pattern: str = "" # 目录模式
    
    def __post_init__(self):
        if self.signature_files is None:
            self.signature_files = []
    
    @property
    def size_display(self) -> str:
        """格式化显示软件大小"""
        return FileInfo.format_size(self.total_size)
    
    def __str__(self) -> str:
        """字符串表示"""
        return f"{self.name} ({self.version}) - {self.category} - {self.size_display}"